import json
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

daily_deals_event_project_api = Blueprint('daily_deals_event_project_api', __name__)
daily_deals_event_project_down_api = Blueprint('daily_deals_event_project_down_api', __name__)


@daily_deals_event_project_api.route('/daily_deals_event_project', methods=['POST'])
def daily_deals_event_project():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        query = DailyDealsEventProject.query.order_by('project').all()
        result = []
        for q in query:
            tmp = {
                "project": int(q.project),
                'remark': q.remark
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'getGemsSum':
        query = DailyDealsEventProject.query.filter_by(project=_project).first()
        gems_sum = 0
        _reward = json.loads(query.reward)
        for i in _reward:
            gems_sum += i['gems']
        result_data['data']['item'] = gems_sum
    elif _action == 'detail':
        query = DailyDealsEventProject.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'reward': json.loads(query.reward)
        }
        result_data['data']['item'] = tmp
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        '''daily_deals_event_project_data = DailyDealsEventProject.query.filter_by(project=_project).first()
        reward = json.loads(daily_deals_event_project_data.reward)'''
        if _part == 'basic':
            DailyDealsEventProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'reward':
            DailyDealsEventProject.query.filter_by(project=_project).update({
                'reward': json.dumps(_data)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'remark':
        newRemark = params['remark']
        DailyDealsEventProject.query.filter_by(project=_project).update({'remark': newRemark})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'clone':  # 克隆方案
        daily_deals_event_project_data = DailyDealsEventProject.query.filter_by(project=_project).first()
        new_project_data = DailyDealsEventProject(
            basic=daily_deals_event_project_data.basic,
            reward=daily_deals_event_project_data.reward,
            remark = daily_deals_event_project_data.remark
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败：id is None"
        else:
            result_data['data']['msg'] = "克隆成功"
    elif _action == 'delete':
        daily_deals_event_project_data = DailyDealsEventProject.query.filter_by(project=_project).first()
        db.session.delete(daily_deals_event_project_data)
        db.session.commit()
        daily_deals_event_project_data = DailyDealsEventProject.query.filter_by(project=_project).first()
        if daily_deals_event_project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'iap_list':
        with open(STATIC_PATH + 'iap_list.json') as f:
            data = json.load(f)
            for i in data:
                i['value'] = i['gem']
                i['label'] = i['label'] + ' - ' + str(i['gem'])
            return json.dumps(data)
    return jsonify(result_data)


@daily_deals_event_project_down_api.route('/daily_deals_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def daily_deals_event_project_down(is_push):
    def get_reward_info(r):
        t = {"a": [r['type'], r['id'], r['num']]}
        return t
    def get_reward_list(a):
        tmp_reward = []
        for i in range(0, len(a)):
            for j in range(0, len(a[i]['reward'])):
                tmp_reward.append(get_reward_info(a[i]['reward'][j]))
        return tmp_reward

    result = {}

    query = DailyDealsEventProject.query.order_by('project').all()

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        reward_data = json.loads(q.reward)

        for i in range(0, len(reward_data)):
            reward_data[i]["chest_id"] = i + 1
            reward_data[i]['reward'] = RewardToTMysqlNew(reward_data[i]['reward'])
        basic['free_chest_reward'] = RewardToTMysqlNew(basic['free_chest_reward'])

        tmp = {
            "basic": {
                "event_ui": basic['event_ui'],
                "discount_ui": basic['discount_ui']
            },
            "info": {
                "iap_pid": 2623,
                "doc_id": basic['doc_id'],
                "chest_doc_id": basic["chest_doc_id"],
                "free_chest_reward": basic["free_chest_reward"],
                "chest_config": reward_data,
                "package_price": basic['package_price'],
                "package_discount": basic['package_discount'],
                "coupon_class": []
            }
        }
        result[_project] = tmp

    response = DownLoad('daily_deals_event_project', result, is_push)

    return response
